package com.xizi.lotterySystem.service.Impl;

import cn.hutool.core.lang.UUID;
import com.xizi.lotterySystem.common.exception.ServiceException;
import com.xizi.lotterySystem.common.exception.errorCode.ServiceErrorCodeConstants;
import com.xizi.lotterySystem.service.IPictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class PictureServiceImpl implements IPictureService {

    @Value(value = "${pic.local-path}")
    private String localPath;

    public String savePicture(MultipartFile file){
        if (file == null || file.isEmpty()) {
            throw new ServiceException(ServiceErrorCodeConstants.UPLOAD_PICTURE_ISNULL);
        }

        // 1.生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;

        // 2. 创建目录
        File dir = new File(localPath);
        if (!dir.exists()) dir.mkdirs();

        // 3️. 保存文件
        File dest = new File(dir, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.UPLOAD_PICTURE_ERROR);
        }

        // 4️. 返回可访问的相对路径
        return fileName;
    }
}
